<?php
/**
 * Created by PhpStorm.
 * User: UEWARE
 * Date: 2019-9-3
 * Time: 17:02:34
 */

namespace App\Http\Controllers\WeChat\Diary\V1\Travels;

use App\Http\Controllers\WeChat\WeChatController;
use App\Models\TravelsModel;
use App\Models\UserModel;
use Illuminate\Http\Request;

class ListController extends WeChatController
{
    /**
     * 列表
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        // 获取
        $data = $request->only('page', 'size');

        $list = TravelsModel::query()
            ->orderBy('created_at', 'desc')
            ->forpage($data['page'] ?? 1, $data['size'] ?? 10)
            ->get()
            ->toArray();

        $count = TravelsModel::query()
            ->count();

        $userId = array_unique(array_column($list, 'user_id'));

        $user = UserModel::query()
            ->whereIn('id', $userId)
            ->get(['id', 'nickname', 'headimgurl'])
            ->toArray();

        $user = array_column($user, null, 'id');

        foreach($list as &$val){
            $val['nickname'] = $user[$val['user_id']]['nickname'];
            $val['headimgurl'] = $user[$val['user_id']]['headimgurl'];
        }

        // 组装数据
        $result['list'] = $list;
        $result['count']['page'] = $data['page'] ?? 1;
        $result['count']['size'] = $data['size'] ?? 10;
        $result['count']['total'] = $count;

        return success($result);
    }
}
